#include "SoftSPI.h"
#include "Delay.h"
#if (defined IO_OBJECT) && (defined IO_BITBAND)
	#error "Select Only One IO Operation"

#elif (defined IO_OBJECT)
	#define MOSI MOSI
	#define MISO MISO
	#define CS CS
	#define SCLK SCLK

#elif (defined IO_BITBAND)
	#define MOSI (*MOSI)
	#define MISO (*MISO)
	#define CS (*CS)
	#define SCLK (*SCLK)

#else
	#error "Select At Least One IO Operation"
#endif
uint8_t SoftSPI::RWByte(uint8_t Byte) const
{
	uint8_t buf;
	CS = 0;
	SCLK = 0;
	MOSI = 0;
	for(int i = 0; i < 8; i++)
	{
		MOSI = (0x80 & Byte) == 0x80;
		Byte <<= 1;
		SCLK = 1;
		Delay.us(2);
		buf <<= 1;
		buf |= MISO & 0x01;
		SCLK = 0;
		Delay.us(2);
	}

	return buf;
}

#ifdef USE_BASICIO
BasicIO::Resault SoftSPI::Read(const uint32_t address, void* buffer, uint32_t length) const
{
	uint8_t* buf = (uint8_t*)buffer;
	CS = 0;
	this->RWByte(address);
	while(length > 0)
	{
		*buf++ = this->RWByte(0x00);
		length -= sizeof(*buf);
	}
	CS = 1;
	return Succ;
}
BasicIO::Resault SoftSPI::Write(const uint32_t address, const void* buffer, uint32_t length) const
{
	uint8_t* buf = (uint8_t*)buffer;
	CS = 0;
	this->RWByte(address);
	while(length > 0)
	{
		this->RWByte(*buf++);
		length -= sizeof(*buf);
	}
	CS = 1;
	return Succ;
}
const BasicIO& SoftSPI::operator >> (uint32_t& Data) const
{
	return *this;
}
const BasicIO& SoftSPI::operator << (const uint32_t Data) const
{
	return *this;
}
#endif


